<template>
  <el-card style="max-width: 100vw">
    <template #header>
      <div class="card-header">
        <span>字典信息管理</span>
        <el-button type="success" @click="openDialog">添加字典信息</el-button>
        <el-input v-model="searchDictName" placeholder="请输入字典名称" style="width: 200px; margin-left: 10px"></el-input>
        <el-button type="primary" @click="searchByDictName">查询</el-button>
      </div>
    </template>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="字典编码" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.dictCode }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="字典名称" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.dictName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="描述" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.description }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">
              {{ scope.row.type === 0 ? 'string' : scope.row.type === 1 ? 'number' : scope.row.type }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="删除标志" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.delFlag }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建者 ID" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.creatorId }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="更新者 ID" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.updatedId }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="220">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.createdTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="220">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.updatedTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
            删除
          </el-button>
          <el-button size="small" type="success" @click="openDictConfigDialog(scope.row)">
            字典配置
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <el-pagination
          background
          layout="prev, pager, next, jumper, sizes"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 30, 40]"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
      />
    </template>
  </el-card>

  <!--  原对话框：字典配置 -->
  <el-dialog
      v-model="dictConfigDialogVisible"
      title="字典配置"
      width="95%"
      style="max-height: 95vh; height: 50vh; overflow-y: auto;"
  >
    <el-table :data="dictConfigTableData"
              style="width: 100%"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="ID" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.id || '未填写ID' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="字典编码" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.dictCode || '未填写字典编码' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="字典项值" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.itemValue || '未填写字典项值' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="字典项中文名称" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.itemCh || '未填写字典项中文名称' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="字典项英文名称" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.itemEn || '未填写字典项英文名称' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="描述" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.description || '未填写描述' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.sortOrder || '未填写排序' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.status || '未填写状态' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建者 ID" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.creatorId}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="更新者 ID" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.updatedId}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="220">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.createdTime ? scope.row.createdTime : '未填写创建时间' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="220">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.updatedTime ? scope.row.updatedTime : '未填写更新时间' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="字典名称" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.dictName || '未填写字典名称' }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-pagination
          background
          layout="prev, pager, next, jumper, sizes"
          :current-page="dictConfigCurrentPage"
          :page-sizes="[5, 10, 20, 30, 40]"
          :page-size="dictConfigPageSize"
          :total="dictConfigTotal"
          @current-change="handleDictConfigCurrentChange"
          @size-change="handleDictConfigSizeChange"
      />
      <!-- 添加删除和添加按钮 -->
      <div style="margin-top: 10px">
        <el-button type="danger" @click="deleteSelectedDictItems">删除选中项</el-button>
        <el-button type="primary" @click="openAddDictItemDialog">添加字典项</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 新增：添加字典项对话框 -->
  <el-dialog
      v-model="addDictItemDialogVisible"
      title="添加字典项"
      width="500px"
  >
    <el-form :model="newDictItem" :rules="addDictItemRules" ref="addDictItemFormRef">
      <el-form-item label="字典项值" prop="itemValue">
        <el-input v-model="newDictItem.itemValue" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="字典项中文" prop="itemCh">
        <el-input v-model="newDictItem.itemCh" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="newDictItem.description" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="newDictItem.type" placeholder="请选择类型">
          <el-option label="string" value="0"></el-option>
          <el-option label="number" value="1"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDictItemDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNewDictItem">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 新增字典信息对话框 -->
  <el-dialog
      v-model="dialogFormVisible"
      :title="title"
      width="500px"
  >
    <el-form :model="form" :rules="rules" ref="formRef">
      <el-form-item label="字典编码" prop="dictCode">
        <el-input v-model="form.dictCode" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="字典名称" prop="dictName">
        <el-input v-model="form.dictName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择类型">
          <el-option label="string" value="0"></el-option>
          <el-option label="number" value="1"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogCancel">取消</el-button>
        <el-button type="primary" @click="dialogConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import {
  getAllSysDict,
  addSysDict,
  searchSysDictByName,
  getDictItemPageListByDictCode,
  deleteDictItemById,
  addDictItem,
  deleteSysDict
} from "@/api/sysDict.js";
import { ElMessageBox, ElMessage } from 'element-plus';

// 定义响应式变量
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const searchDictName = ref(''); // 新增：用于存储输入的字典名称
const type = ref(0);

// 新对话框相关变量
const dictConfigDialogVisible = ref(false);
const dictConfigTableData = ref([]);
const dictConfigCurrentPage = ref(1);
const dictConfigPageSize = ref(10);
const dictConfigTotal = ref(0);
const selectedDictCode = ref('');
const selectedDictItems = ref([]); // 新增：用于存储选中的字典项
const addDictItemDialogVisible = ref(false); // 新增：添加字典项对话框的显示状态
const newDictItem = ref({
  dictCode: '',
  itemValue: '',
  itemCh: '',
  description: '',
  type: 0
}); // 新增：用于存储新添加的字典项信息
const addDictItemRules = reactive({
  itemValue: [
    { required: true, message: '请输入字典项值', trigger: 'blur' }
  ],
  itemCh: [
    { required: true, message: '请输入字典项中文', trigger: 'blur' }
  ]
});
const addDictItemFormRef = ref(null);

// dialog区域
// 该常量主要控制 Dialog 的开关
const dialogFormVisible = ref(false);

// Dialog 标题常量
const title = ref('添加字典信息');

// dialog 里面表单里面的元素的宽度
// 该常量只 Form 组件里面的规则，formLabelWidth 是控制宽度
const formLabelWidth = '140px';

// todo form 表单对象数据
// 该常量是 Form 表单里面绑定的数据
const form = ref({
  dictCode: '',
  dictName: '',
  description: '',
  // 确保 type 初始值为数字 0
  type: 0
});

const rules = reactive({
  dictCode: [
    { required: true, message: '请输入字典编码', trigger: 'blur' }
  ],
  dictName: [
    { required: true, message: '请输入字典名称', trigger: 'blur' }
  ]
});

const formRef = ref(null);

// 修改 fetchData 函数，支持传递 dictName 参数
const fetchData = async (dictName = '') => {
  type.value = 0;
  try {
    const response = await getAllSysDict(currentPage.value, pageSize.value, dictName);
    if (response.data.code === 200) {
      tableData.value = response.data.data.records;
      total.value = response.data.data.total;
    }
  } catch (error) {
    console.error('获取字典数据失败:', error);
  }
};

// 新增：按照字典名称模糊查询函数
const searchByDictName = async () => {
  type.value = 1;
  try {
    const response = await searchSysDictByName(currentPage.value, pageSize.value, searchDictName.value);
    if (response.data.code === 200) {
      tableData.value = response.data.data.records;
      total.value = response.data.data.total;
    }
  } catch (error) {
    console.error('按字典名称查询失败:', error);
  }
};

// 新函数：根据字典编码获取字典项分页列表
const fetchDictConfigData = async () => {
  try {
    const response = await getDictItemPageListByDictCode(
        dictConfigCurrentPage.value,
        dictConfigPageSize.value,
        selectedDictCode.value
    );
    if (response.data.code === 200) {
      dictConfigTableData.value = response.data.data.records;
      dictConfigTotal.value = response.data.data.total;
    }
  } catch (error) {
    console.error('获取字典项数据失败:', error);
  }
};

// 新函数：打开字典配置对话框
const openDictConfigDialog = (row) => {
  selectedDictCode.value = row.dictCode;
  dictConfigCurrentPage.value = 1;
  fetchDictConfigData();
  dictConfigDialogVisible.value = true;
};

// 新函数：字典配置对话框页码改变时触发
const handleDictConfigCurrentChange = (val) => {
  dictConfigCurrentPage.value = val;
  fetchDictConfigData();
};

// 新函数：字典配置对话框每页显示条数改变时触发
const handleDictConfigSizeChange = (val) => {
  dictConfigPageSize.value = val;
  fetchDictConfigData();
};

// 初始化加载所有数据
onMounted(() => {
  fetchData();
});

// 页码改变时触发
const handleCurrentChange = (val) => {
  currentPage.value = val;
  // 传递 searchDictName.value
  if (type.value === 1) {
    searchByDictName(); // 执行按字典名称模糊查询
  } else {
    fetchData(); // 执行查询所有
  }
};

// 每页显示条数改变时触发
const handleSizeChange = (val) => {
  pageSize.value = val;
  if (type.value === 1) {
    searchByDictName(); // 执行按字典名称模糊查询
  } else {
    fetchData(); // 执行查询所有
  }
};

// todo dialog 取消事件
// 该函数是 dialog 里面的取消按钮的操作
const dialogCancel = () => {
  dialogFormVisible.value = false;
  console.log("dialog 取消操作...............");
  // 重置表单数据
  form.value = {
    dictCode: '',
    dictName: '',
    description: '',
    type: 0
  };
};

// todo dialog 确定事件
// 该函数是 dialog 里面的确定按钮的操作
const dialogConfirm = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      const response = await addSysDict(form.value);
      if (response.data.code === 200) {
        // 操作成功
        ElMessageBox.alert(response.data.message, '提示', {
          type: 'success',
        });
      } else {
        // 操作失败
        ElMessageBox.alert(response.data.message, '提示', {
          type: 'error',
        });
      }
      dialogFormVisible.value = false;
      // 重置表单数据
      form.value = {
        dictCode: '',
        dictName: '',
        description: '',
        type: 0
      };
      // 重新获取数据刷新表格
      fetchData();
    } catch (error) {
      let errorMessage = '添加字典数据失败，请稍后重试';
      // 检查 error 对象是否包含响应信息
      if (error.response && error.response.data && error.response.data.message) {
        errorMessage = error.response.data.message;
      }
      console.error('添加字典数据失败:', error);
      ElMessageBox.alert(errorMessage, '提示', {
        type: 'error',
      });
    }
  });
};

// todo 打开 Dialog 函数
// 该函数是弹出 dialog
const openDialog = () => {
  console.log("dialog 框弹出来了...............");
  dialogFormVisible.value = true;
};

// todo 关闭 Dialog 函数
// 该函数是关闭 dialog
const closeDialog = () => {
  dialogFormVisible.value = false;
  console.log("dialog 关闭了...............");
};

// 新增：处理表格选中项变化
const handleSelectionChange = (val) => {
  selectedDictItems.value = val;
};

// 新增：删除选中的字典项
const deleteSelectedDictItems = async () => {
  if (selectedDictItems.value.length === 0) {
    ElMessage.warning('请选择要删除的字典项');
    return;
  }
  try {
    await ElMessageBox.confirm('确定要删除选中的字典项吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    for (const item of selectedDictItems.value) {
      await deleteDictItemById(item.id);
    }
    ElMessage.success('删除成功');
    fetchDictConfigData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请稍后重试');
      console.error('删除字典项失败:', error);
    }
  }
};

// 新增：打开添加字典项对话框
const openAddDictItemDialog = () => {
  newDictItem.value = {
    dictCode: selectedDictCode.value,
    itemValue: '',
    itemCh: '',
    description: '',
    type: 0
  };
  addDictItemDialogVisible.value = true;
};

// 新增：保存新添加的字典项
const saveNewDictItem = async () => {
  if (!addDictItemFormRef.value) return;
  addDictItemFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      const response = await addDictItem(newDictItem.value);
      if (response.data.code === 200) {
        ElMessage.success('添加成功');
        addDictItemDialogVisible.value = false;
        fetchDictConfigData();
      } else {
        ElMessage.error(response.data.message || '添加失败，请稍后重试');
      }
    } catch (error) {
      console.error('添加字典项失败:', error);
      ElMessage.error('添加字典项失败，请稍后重试');
    }
  });
};

// 新增：删除主表格中的字典信息
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该字典信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const response = await deleteSysDict(id);
    if (response.data.code === 200 && response.data.data) {
      ElMessage.success('删除成功');
      fetchData();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败，请稍后重试');
      console.error('删除字典信息失败:', error);
    }
  }
};
</script>

<style scoped>
.card-header {
  display: flex;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>